package com.tust.androidreader;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Calendar;
import java.util.Objects;

public class AddBookActivity extends AppCompatActivity {
    private Toast toast;
    private int bookCount;
    private int wordNum;

    //权限获取的启动器
    ActivityResultLauncher<String[]> launcher = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), result -> {//注册权限获取的启动器
        if (result.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) != null && result.get(Manifest.permission.READ_EXTERNAL_STORAGE) != null) {//检查是否动态申请权限
            if (Objects.requireNonNull(result.get(Manifest.permission.WRITE_EXTERNAL_STORAGE)).equals(true) && Objects.requireNonNull(result.get(Manifest.permission.READ_EXTERNAL_STORAGE)).equals(true)) {//权限全部获取到之后的动作
                showToast("权限获取成功！");
            } else {//有权限没有获取到的动作
                showToast("没有足够的权限！");
            }
        }
    });

    //activity选择器的回调方法的启动器
    ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {//activity选择器的回调方法
            int resultCode;
            if ((resultCode = result.getResultCode()) == Activity.RESULT_OK) {
                Intent data = result.getData();
                if (resultCode == Activity.RESULT_OK) {
                    try {
                        String fileName = "data/data/com.tust.androidreader/b" + bookCount + ".txt";
                        File file = new File(fileName);
                        FileOutputStream fileOutputStream = new FileOutputStream(file);
                        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);

                        Uri uri = data.getData();//获取URI
                        InputStream inputStream = getContentResolver().openInputStream(uri);//获取输入流
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                        int c;//保存读取到的内容
                        wordNum = 0;//字数计数器
                        while ((c = bufferedReader.read()) != -1) {
                            outputStreamWriter.write(c);
                            wordNum++;
                        }
                        wordNum = wordNum / 2;

                        bufferedReader.close();
                        outputStreamWriter.flush();
                        outputStreamWriter.close();
                        fileOutputStream.flush();
                        fileOutputStream.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_book);

        DBHelper dbHelper = new DBHelper(this);
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        Cursor bookCursor = db.rawQuery("select * from book", null);
        bookCount = bookCursor.getCount();
        bookCursor.close();

        Button buttonBookContent = this.findViewById(R.id.bt_bookcontent);
        Button buttonCheckBookFile = this.findViewById(R.id.bt_checkbookfile);
        EditText editTextBookName = this.findViewById(R.id.et_bookname);
        EditText editTextAuthor = this.findViewById(R.id.et_author);
        EditText editTextClassify = this.findViewById(R.id.et_classify);
        Button buttonAddBook = this.findViewById(R.id.bt_addbook);
        Button buttonBackToLibrary = this.findViewById(R.id.bt_backtolibrary);

        buttonBookContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                launcher.launch(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE});//调用启动器动态申请写入和读取存储权限

                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("text/*");//筛选器
                intent.addCategory(Intent.CATEGORY_OPENABLE);

                activityResultLauncher.launch(Intent.createChooser(intent,"选择一个txt"));
            }
        });

        buttonCheckBookFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (fileIsExists("data/data/com.tust.androidreader/b" + bookCount + ".txt")) {
                    showToast("导入成功");
                    buttonCheckBookFile.setBackgroundColor(Color.rgb(255,255,0));
                } else {
                    showToast("导入失败！");
                }
            }
        });

        buttonBackToLibrary.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AddBookActivity.this,LibraryActivity.class);
                startActivity(intent);
            }
        });

        buttonAddBook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String bookName = editTextBookName.getText().toString();
                String author = editTextAuthor.getText().toString();
                String classify = editTextClassify.getText().toString();
                if (!fileIsExists("data/data/com.tust.androidreader/b" + bookCount + ".txt")) {
                    showToast("书籍文件不存在！");
                } else if (bookName.equals("")) {
                    showToast("书名不能为空！");
                } else if (author.equals("")) {
                    showToast("作者不能为空！");
                } else if (classify.equals("")) {
                    showToast("分类不能为空！");
                } else if (bookName.equals("输入书名")) {
                    showToast("请输入书名！");
                } else if (author.equals("输入作者")) {
                    showToast("请输入作者！");
                } else if (classify.equals("输入分类")) {
                    showToast("请输入分类！");
                } else {
                    Cursor cursor = db.rawQuery("select * from book where bookname = ?", new String[]{bookName});
                    if (cursor.getCount() > 0) {//书名重复
                        showToast("书名已存在！");
                        cursor.close();
                        return;
                    }
                    cursor.close();

                    Calendar calendar = Calendar.getInstance();//获取导入时间
                    int year = calendar.get(Calendar.YEAR);
                    int month = calendar.get(Calendar.MONTH) + 1;//月份起始是0
                    int date = calendar.get(Calendar.DATE);
                    String addTime = year + "/" + month + "/" + date;

                    db.execSQL("insert into book values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", new Object[]{R.drawable.b0, bookName, author, "0", "0", "0", classify, addTime, wordNum, "data/data/com.tust.androidreader/b" + bookCount + ".txt", 0});
                    showToast("导入成功！");

                    Intent intent = new Intent(AddBookActivity.this,LibraryActivity.class);
                    startActivity(intent);
                }
            }
        });
    }

    public boolean fileIsExists(String fileName) {//判断文件是否存在
        try {
            File f=new File(fileName);
            if(f.exists()) {
                Log.i("fileIsExists", "有这个文件");
                return true;
            }else{
                Log.i("fileIsExists", "没有这个文件");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private void showToast(String s) {
        if (toast == null){
            toast = Toast.makeText(this, s, Toast.LENGTH_SHORT);
        }else {
            toast.cancel();
            toast = Toast.makeText(this, s, Toast.LENGTH_SHORT);
        }
        toast.show();
    }
}